<template>
  <!-- 单行文本、 多行文本、 数字-->
  <van-lc-field
    v-validate="fieldValidate"
    v-if="item.field_type==='text'||item.field_type==='textarea'||item.field_type==='number'"
    v-bind="$attrs"
    :label="label"
    :desc="item.desc"
    :placeholder="placeholder"
    :type="item.field_type"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    autosize
    clearable
    v-on="$listeners"
  />
  <!-- 单项选择 -->
  <van-lc-radio
    v-validate="fieldValidate"
    v-else-if="item.field_type==='radio'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :options="options"
    :other-option-value="otherOptionValue"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    value-key="val"
    v-on="$listeners"
    @change-other-option="changeOtherOption"
  />

  <!-- 多项选择 -->
  <van-lc-checkbox
    v-validate="fieldValidate"
    v-else-if="item.field_type==='checkbox'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :other-option-value="otherOptionValue"
    :options="options"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    value-key="val"
    v-on="$listeners"
    @change-other-option="changeOtherOption"
  />
  <!-- 下拉选择 -->
  <van-lc-picker
    v-validate="fieldValidate"
    v-else-if="item.field_type==='select'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="selectPlaceholder"
    :options="options"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    value-key="val"
    v-on="$listeners"
  />
  <!-- 日期/ 当前时间、当前日期 -->
  <van-lc-date-picker
    v-validate="fieldValidate"
    v-else-if="item.field_type==='datePicker'|| item.field_type==='currentDate'|| item.field_type==='currentTime'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :type="'custom'"
    :format="dateFormat"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"
  />
  <!-- 富文本 -->
  <van-lc-editor
    v-validate="fieldValidate"
    v-else-if="item.field_type==='editor'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :height="height"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"
  />
  <!-- 数据字典 -->
  <van-lc-dictionary
    v-validate="fieldValidate"
    v-else-if="item.field_type==='dictionary'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :cat-type="fieldOptions.dictionary"
    :select-mode="fieldOptions.select_mode"
    :display-mode="fieldOptions.display_mode"
    :separator="fieldOptions.separator"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"

  />
  <!-- 自动编号 -->
  <van-lc-auto-number
    v-validate="fieldValidate"
    v-else-if="item.field_type==='autoNumber'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :identity="fieldOptions.identity"
    :init="$utils.toBoolean(fieldOptions.init)"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"

  />
  <!-- 上传附件 -->
  <van-lc-uploader
    v-validate="fieldValidate"
    v-else-if="item.field_type==='attachment'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :store="fieldOptions.store||'json'"

    :max-size="maxFileSize"
    :file-quantity="fileQuantity"
    :accept="accept"
    :file-formates="fileFormates"

    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"
  />

  <!-- 选择器 -->
  <van-lc-selector
    v-validate="fieldValidate"
    v-else-if="item.field_type==='selector' || item.field_type==='currentUser'|| item.field_type==='currentOrg'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :store="fieldOptions.store||'json'"
    :type="fieldOptions.selector_type||'user'"
    :multiple="multiple"
    :bind-id="bindId"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    @bind-callback ="selectorBindCallback"
    v-on="$listeners"
  />
  <!-- 自定义对话框 -->
  <van-lc-custom-dialog
    v-validate="fieldValidate"
    v-else-if="item.field_type==='customDialog'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :multiple="multiple"
    :template-key="fieldOptions.dialog"
    :store="fieldOptions.store"
    :field-options="fieldOptions"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"
    @callback="dialogCallback"
    @attr-callback="dialogAttrCallback"
  />
  <!-- 关联数据 -->
  <van-lc-linkdata
    v-validate="fieldValidate"
    v-else-if="item.field_type==='linkdata'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :multiple="multiple"
    :template-key="fieldOptions.linkdata"
    :store="fieldOptions.store"
    :name="item.name"
    :field-options="fieldOptions"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"
    @callback="linkdataCallback"
    @attr-callback="linkdataAttrCallback"
  />

  <!-- 地址 -->
  <van-lc-address
    v-validate="fieldValidate"
    v-else-if="item.field_type==='address'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :top="fieldOptions.top"
    :top-val="getAddressTopVal()"
    :level="fieldOptions.level"
    :has-street="fieldOptions.is_street"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"
  />

  <!-- 签名 -->
  <van-lc-signature
    v-validate="fieldValidate"
    v-else-if="item.field_type==='signature'"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :placeholder="placeholder"
    :height="height"
    :name="item.name"
    :required="required"
    :error="errors.has(item.name)"
    :error-message="errors.first(item.name)"
    v-on="$listeners"
  />
  <!-- 子表 -->
  <van-lc-table
    v-else-if="item.field_type==='table'"
    ref="formItem"
    v-bind="$attrs"
    :label="item.label"
    :desc="item.desc"
    :item="item"
    :readonly="params.readonly"
    :permissions="params.permissions[item.name]"
    :response-formula="params.responseFormula"
    :form-data="formData"
    @change-form-data="changeFormData($event)"
    v-on="$listeners"
  />

  <!-- 隐藏域-->
  <input
    v-else-if="item.field_type==='hidden'"
    v-bind="$attrs"
    type="hidden"
    v-on="$listeners"
  >

  <!-- 描述-->
  <van-lc-desc
    v-else-if="item.field_type==='desc'"
    v-bind="$attrs"
    :label="item.label"
    :border="fieldOptions.split_line"
    :desc="item.desc"
    :border-style="fieldOptions.line_style"
    v-on="$listeners"
  />

  <!-- 文本-->
  <van-lc-label
    v-else-if="item.field_type==='label'"
    v-bind="$attrs"
    :label="item.label"
    :class="$attrs.hidden"
    v-on="$listeners"
  />

  <!-- 审批历史-->
  <div
    v-else-if="item.field_type === 'approval_history'">
    <van-lc-approval-history
      v-if="showApprovalHistory"
      :label="item.label"
      :task-id="params.taskId"
      :bpmn-inst-id="params.bpmnInstId"
    />
  </div>

  <!-- 流程图-->
  <div
    v-else-if="item.field_type === 'flow_diagram'">
    <van-lc-flow-diagram
      v-if="showFlowDiagram"
      :label="item.label"
      :def-id="params.defId"
      :task-id="params.taskId"
      :bpmn-inst-id="params.bpmnInstId"
    />
  </div>
  <!-- 选项卡-->
  <div
    v-else-if="item.field_type==='tab_break'"
    class="van-tabs__nav van-tabs__nav--card lc-tab-break">
    <div
      class="van-tab van-tab--active van-ellipsis lc-tab-break--label"
      v-html="item.label"/>
  </div>
  <!-- office目前版本不支持-->
  <span v-else-if="item.field_type==='office'"/>
  <!-- 审批意见目前版本不支持-->
  <span v-else-if="item.field_type==='approval_opinion'"/>
  <!-- 分页 -->
  <span v-else-if="item.field_type==='page_break'"/>
  <!-- 折叠卡 -->
  <span v-else-if="item.field_type==='fold_card'"/>

  <span v-else-if="item.field_type==='section_break'"/>
  <span v-else>未支持控件类型[{{ item.field_type }}]</span>
</template>
<script>
// import request from '@/utils/request'
import FormOptions from './constants/formoptions'
import { fileTypes as FILE_TYPES, accept as ACCEPT } from '@/constants/file'

export default {
  props: {
    item: {
      type: Object,
      required: true
    },
    required: {
      type: Boolean
    },
    data: {
      type: Object
    },
    params: {
      type: Object
    }
  },
  data() {
    return {
      ajaxOptions: []
    }
  },
  computed: {
    formData() {
      return this.data
    },
    // 表单验证
    fieldValidate() {
      const v = {}
      // 必填验证
      if (this.required) {
        v.required = true
      }
      // 整型验证
      if (this.fieldOptions['integer']) {
        v.integer = true
      }
      // 最大、最小字符串长度验证
      if (this.fieldOptions['min_length']) {
        v.min = this.fieldOptions['min_length']
      }
      if (this.fieldOptions['max_length']) {
        v.max = this.fieldOptions['max_length']
      }
      // 最大、最小值验证
      if (this.fieldOptions['min']) {
        v.min_value = this.fieldOptions['min']
      }
      if (this.fieldOptions['max']) {
        v.max_value = this.fieldOptions['max']
      }
      // 小数验证
      if (this.fieldOptions['decimal']) {
        v.decimal = this.fieldOptions['decimal']
      }

      // 日期验证 date_format 不需要

      // TODO 日期范围验证-开始、结束时间 date_between

      // 多少项验证 （主要是多选用）
      if (this.fieldOptions['min_mum']) {
        v.min_mum = this.fieldOptions['min_mum']
      }
      if (this.fieldOptions['max_mum']) {
        v.max_mum = this.fieldOptions['max_mum']
      }
      // 正则表达式
      if (this.fieldOptions['data_format']) {
        v.regexp = [
          this.fieldOptions['data_format'],
          this.fieldOptions['data_format_value'],
          this.fieldOptions['data_format_msg']
        ]
      }
      return v
    },
    fieldOptions() {
      return this.item.field_options || {}
    },
    label() {
      if (this.$utils.isNotEmpty(this.fieldOptions.units)) {
        return this.item.label + '(' + this.fieldOptions.units + ')'
      }
      return this.item.label
    },
    // 日期格式
    dateFormat() {
      if (this.item.field_type === 'currentDate') {
        return FormOptions.t.DATE_FORMATS['date']
      } else if (this.item.field_type === 'currentTime') {
        return FormOptions.t.DATE_FORMATS['datetime']
      } else {
        if (this.fieldOptions['datefmt_type'] && this.fieldOptions['datefmt_type'] !== 'custom') {
          return FormOptions.t.DATE_FORMATS[this.fieldOptions['datefmt_type']] || FormOptions.t.DATE_FORMATS['date']
        }
        return this.fieldOptions['datefmt'] || FormOptions.t.DATE_FORMATS['date']
      }
    },
    /**
     * 单选、多选、下拉等选项
     */
    options() {
      return this.fieldOptions['options'] || []
    },
    /**
     *  占位符
     */
    placeholder() {
      return !this.$attrs.readonly ? this.fieldOptions['placeholder'] : ''
    },
    /**
     * 下拉占位符
     */
    selectPlaceholder() {
      return !this.$attrs.readonly ? (this.fieldOptions['include_blank_value'] || this.fieldOptions['placeholder']) : ''
    },
    /**
     * 最大文件上传
     */
    maxFileSize() {
      if (this.$utils.isNotEmpty(this.fieldOptions.max_file_size)) {
        return this.fieldOptions.max_file_size * 1024 * 1024
      }
    },
    /**
     * 最大文件个数
     */
    fileQuantity() {
      const fileQuantity = this.fieldOptions.max_file_quantity
      if (this.$utils.isNotEmpty(fileQuantity) && (fileQuantity !== '-1' || fileQuantity !== -1)) {
        return parseInt(fileQuantity, 10)
      }
    },
    accept() {
      const mediaType = this.fieldOptions.media_type
      if (this.$utils.isEmpty(mediaType)) { return '*' }
      const x = ACCEPT[mediaType]
      if (x) {
        return x
      } else {
        return '*'
      }
    },
    fileFormates() {
      const mediaType = this.fieldOptions.media_type
      if (this.$utils.isEmpty(mediaType)) { return [] }
      const x = FILE_TYPES[mediaType]
      if ((x)) {
        return x.map((v) => {
          return '.' + v
        })
      } else {
        return (this.fieldOptions.media || '').split(',')
      }
    },
    bindId() {
      var bindId = this.fieldOptions['bind_id']
      if (this.$utils.isEmpty(bindId)) { return '' }
      return this.formData[bindId] || ''
    },

    /**
     * 是否多选
     */
    multiple() {
      return !this.$utils.toBoolean(this.fieldOptions['is_single'])
    },
    height() {
      return this.fieldOptions.height ? parseInt(this.fieldOptions.height, 10) : null
    },
    // 是否显示审批历史
    showApprovalHistory() {
      return !!(this.params.taskId || this.params.bpmnInstId)
    },
    // 是否显示流程图
    showFlowDiagram() {
      return !!(this.params.defId || this.params.taskId || this.params.bpmnInstId)
    },
    otherOptionValue() {
      return this.getOtherOptionValue()
    }
  },
  methods: {
    changeOtherOption(value) {
      const otherId = this.fieldOptions['option_other_id']
      if (this.$utils.isEmpty(otherId)) return
      const formData = this.$utils.newData(this.formData)
      formData[otherId] = value
      this.changeFormData(formData)
    },
    getOtherOptionValue() {
      const otherId = this.fieldOptions['option_other_id']
      if (this.$utils.isEmpty(otherId)) return
      return this.formData[otherId] || ''
    },
    getAddressTopVal() {
      var top = this.fieldOptions.top
      var topval = this.fieldOptions.topval
      if (this.$utils.isEmpty(topval)) {
        if (top === 'country') {
          return '0'
        }
        return '' // 异常配置
      }
      if (top === 'country') {
        return '0'
      } else if (top === 'province') {
        return topval['country'] + ''
      } else if (top === 'city') {
        return topval['province'] + ''
      } else if (top === 'district') {
        return topval['city'] + ''
      }
      return ''
    },
    /**
     * 对话框回调
     */
    dialogCallback(data, params) {
      const bind = this.getBind()
      if (this.$utils.isEmpty(bind)) { return }
      // 设置联动数据
      const formData = this.$utils.newData(this.formData)
      bind.forEach(obj => {
        const name = obj.name
        const field = obj.fieldName
        if (this.$utils.isEmpty(name) || this.$utils.isEmpty(field)) { return true }
        // TODO  目前只支持主表  数据处理没做
        const value = data.map((d) => {
          return d[field]
        }).join(',')
        formData[name] = value
      })
      this.changeFormData(formData)
    },
    /**
     * 对话框回调
     */
    // TODO pc 端做这个功能再做
    dialogAttrCallback(data, params) {

    },
    /**
     * 关联数据回调
     */
    linkdataCallback(data, params) {
      const linkLinkage = this.getLinkLinkage()
      const linkAttr = this.getLinkAttr()
      if (this.$utils.isEmpty(linkLinkage) && this.$utils.isEmpty(linkAttr)) { return }

      // 设置联动数据
      const formData = this.$utils.newData(this.formData)
      linkLinkage.forEach(obj => {
        const name = obj.name
        const field = obj.field
        if (this.$utils.isEmpty(name) || this.$utils.isEmpty(field)) { return true }
        // TODO  目前只支持主表  数据处理没做
        const value = data.map((d) => {
          return d[field]
        }).join(',')
        formData[name] = value
      })

      this.linkageChangeFormData(linkAttr, formData, data, params)
    },
    /**
     * 关联数据---关联属性
     */
    linkdataAttrCallback(data, params) {
      const linkAttr = this.getLinkAttr()
      if (this.$utils.isEmpty(linkAttr)) { return }
      const formData = this.$utils.newData(this.formData)
      this.linkageChangeFormData(linkAttr, formData, data, params)
    },
    /**
     * 关联数据----联动改变表单数据
     */
    linkageChangeFormData(linkAttr, formData, data, params) {
      if (this.$utils.isNotEmpty(linkAttr)) {
      // 关联属性
        linkAttr.forEach(obj => {
          const name = obj.name
          const field = obj.field
          if (this.$utils.isEmpty(name) || this.$utils.isEmpty(field)) { return true }
          // TODO  目前只支持主表  数据处理没做
          const value = data.map((d) => {
            return d[field]
          }).join(',')
          formData[name] = value
        })
      }
      this.changeFormData(formData)
    },
    getLinkLinkage() {
      return this.fieldOptions['link_linkage'] || []
    },
    getLinkAttr: function() {
      return this.fieldOptions['link_attr'] || []
    },
    getBind: function() {
      return this.fieldOptions['bind'] || []
    },
    getBindId: function() {
      return this.fieldOptions['bind_id'] || ''
    },
    selectorBindCallback(data) {
      var bindId = this.getBindId()
      if (this.$utils.isNotEmpty(bindId)) {
        const formData = this.$utils.newData(this.formData)
        formData[bindId] = data
        this.changeFormData(formData)
      } else {
        this.$toast('[' + this.label + ']字段未绑Id')
      }
    },
    getEl() {
      return this.$refs.formItem.getEl()
    },
    /**
     * 改变表单的数据
     */
    changeFormData(data) {
      this.$emit('change-form-data', data)
    }
  }
}
</script>

